package com.hzdp.netty.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class UdpClient {

	public void run(int port) throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();

		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
					.handler(new SimpleChannelInboundHandler<DatagramPacket>() {
						@Override
						protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
							System.out.println(msg.content().toString(CharsetUtil.UTF_8));
						}
					});
			Channel channel = b.bind(0).sync().channel();
			channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("hell", CharsetUtil.UTF_8), new InetSocketAddress("255.255.255.255", port))).sync();

			if (!channel.closeFuture().await(15000)) {
				System.out.println("超时");
			}
		} finally {
			group.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		new UdpClient().run(8080);
	}
}
